package com.bestcem.xm.member.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.message.ProjectMapEntity;
import com.bestcem.xm.common.core.domain.message.RespondentSeq;
import com.bestcem.xm.common.core.domain.message.SampleCopyMessage;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.sql.ConditionConstant;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.common.core.uitls.JsonUtil;
import com.bestcem.xm.common.core.uitls.StringUtil;
import com.bestcem.xm.label.dao.LabelDao;
import com.bestcem.xm.label.dao.LabelGroupDao;
import com.bestcem.xm.label.dao.LabelValueDao;
import com.bestcem.xm.label.entity.pojo.LabelDO;
import com.bestcem.xm.label.entity.pojo.LabelGroupDO;
import com.bestcem.xm.label.entity.pojo.LabelValueDO;
import com.bestcem.xm.member.dao.*;
import com.bestcem.xm.member.entity.mongo.ExtendFieldValue;
import com.bestcem.xm.member.entity.mysql.LabelValueId;
import com.bestcem.xm.member.entity.pojo.*;
import com.bestcem.xm.member.enums.ExtendFieldTypeEnum;
import com.bestcem.xm.member.enums.FootprintTypeEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.enums.NewMemberStatusEnum;
import com.bestcem.xm.member.grpc.client.SurveyClient;
import com.bestcem.xm.member.grpc.client.TicketClient;
import com.bestcem.xm.member.grpc.client.UserClient;
import com.bestcem.xm.member.mq.message.MemberMessage;
import com.bestcem.xm.member.service.MemberSampleMqHandler;
import com.bestcem.xm.member.service.MemberService;
import com.bestcem.xm.member.service.dto.ExtendFieldDTO;
import com.bestcem.xm.member.service.dto.OrganizationDTO;
import com.bestcem.xm.member.util.MemberUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.common.core.sql.ConditionConstant.*;
import static com.bestcem.xm.common.core.sql.ConditionConstant.FieldTypes.LABEL;
import static com.bestcem.xm.member.constant.ColumnConstant.Member.SOURCE;
import static com.bestcem.xm.member.constant.Constants.EMPLOYEE_STATUS_MAP;

/**
 * 联系人行业sample
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/10/18
 */
@Slf4j
@Service
public class MemberSampleMqHandlerImpl implements MemberSampleMqHandler {

    @Resource
    private MemberDao memberDao;

    @Resource
    private FootprintDao footprintDao;

    @Resource
    private LabelGroupDao labelGroupDao;

    @Resource
    private LabelDao labelDao;

    @Resource
    private LabelValueDao labelValueDao;

    @Resource
    private TicketClient ticketClient;

    @Resource
    private SurveyClient surveyClient;

    @Resource
    private MemberService memberService;

    @Resource
    private MemberUtil memberUtil;

    @Resource
    private GroupDao groupDao;

    @Resource
    private ExtendFieldDao extendFieldDao;

    @Resource
    private ExtendFieldEnumItemDao extendFieldEnumItemDao;

    @Resource
    ProjectDao projectDao;

    @Resource
    UserClient userClient;

    @Override
    public void memberSampleCopy(SampleCopyMessage copyMessage, Map<String, String> ticketIdMap) {
        if (log.isInfoEnabled()) {
            log.info("接收到的消息 {}", JSONObject.toJSONString(copyMessage));
        }

        log.error("接收到的消息 {}", JSONObject.toJSONString(copyMessage));

        String orgSrcId = copyMessage.getOrgSrcId();
        String orgDstId = copyMessage.getOrgDstId();
        Boolean isSample = copyMessage.getIsSample();

        if (StrUtil.isBlank(orgSrcId)) {
            log.error("【Member】Sample Src OrgId 不存在");
            return;
        }

        if (StrUtil.isBlank(orgDstId)) {
            log.error("【Member】Sample Dst OrgId 不存在");
            return;
        }

        if (Objects.isNull(isSample)) {
            log.error("【Member】Sample isSample字段 不存在");
            return;
        }

        // 标签id map
        Map<String, String> labelIdMap = new HashMap<>();
        // 标签值id map
        Map<String, String> labelValueIdMap = new HashMap<>();
        // 联系人组织层级旧新id map
        Map<String, String> groupIdMap = userClient.listGroupIdMaps(orgSrcId, orgDstId);

        // 获取联系人、项目拓展字段
        List<Integer> memberTypes = Arrays.asList(MemberTypeEnum.INDIVIDUAL.getIndex(),
                MemberTypeEnum.INSTITUTION.getIndex(),
                MemberTypeEnum.INTERIOR.getIndex(),
                MemberTypeEnum.HIDDEN.getIndex(),   // 兼容老数据
                MemberTypeEnum.PROJECT.getIndex());
        List<ExtendFieldDO> extendFields = extendFieldDao.listByOrgIdAndMemberTypes(orgSrcId, memberTypes);
        // 获取联系人、项目拓展字段枚举值查询范围
        List<String> extendFieldIds = extendFields.stream()
                .filter(extendFieldDO -> extendFieldDO.getType().equals(ExtendFieldTypeEnum.ENUM.getIndex()))
                .map(ExtendFieldDO::getFieldId)
                .collect(Collectors.toList());
        // 联系人、项目拓展字段旧新id map
        Map<String, String> extendFieldIdMap = new HashMap<>();
        // 处理联系人、项目拓展字段
        buildExtendFieldDataAndSave(orgDstId, extendFields, extendFieldIdMap);
        // 获取联系人、项目拓展字段枚举值
        Collection<ExtendFieldEnumItemDO> extendFieldEnumItems = extendFieldEnumItemDao.findByFieldIds(extendFieldIds);
        // 处理联系人、项目拓展字段枚举值数据
        buildExtendFieldEnumItemDataAndSave(extendFieldEnumItems, extendFieldIdMap);

        // 获取标签组、标签、标签值
        List<LabelGroupDO> labelGroups = labelGroupDao.listByOrgId(orgSrcId);
        List<LabelDO> labels = labelDao.listByOrgId(orgSrcId);
        List<LabelValueDO> labelValues = labelValueDao.listByOrgIdAndMemberType(orgSrcId, MemberTypeEnum.INDIVIDUAL.getIndex());
        // 处理标签数据
        buildLabelDataAndSave(labelGroups, labels, labelValues, orgDstId, labelIdMap, labelValueIdMap, copyMessage.getProjectList(), groupIdMap, extendFieldIdMap, isSample);

        // 获取分组
        List<GroupDO> groups = groupDao.findByOrgId(orgSrcId);
        // 分组旧新seq map
        Map<Long, Long> groupSeqMap = new HashMap<>();
        // 处理分组数据
        buildGroupDataAndSave(groups, orgSrcId, orgDstId, groupSeqMap, extendFieldIdMap, labelIdMap, labelValueIdMap, groupIdMap, isSample);

        // 获取联系人
        List<MemberDO> memberList = memberDao.findByOrgIdAndStatus(orgSrcId, NewMemberStatusEnum.MEMBER_STATUS_ACTIVATED.getIndex());
        if (!isSample) {
            memberList = memberList.stream()
                    .filter(memberDO -> !memberDO.getMemberType().equals(MemberTypeEnum.INTERIOR.getIndex()))
                    .collect(Collectors.toList());
        }
        // 获取足迹点
        List<FootprintDO> footprints = footprintDao.findByOrgId(orgSrcId);
        // 机构、内部联系人旧新id map
        Map<String, String> insIntMemberIdMap = new HashMap<>();
        // 处理联系人数据
        buildMemberDataAndSave(memberList, footprints, orgSrcId, orgDstId, copyMessage.getSeqList()
                , ticketIdMap, labelIdMap, labelValueIdMap, groupSeqMap, insIntMemberIdMap, extendFieldIdMap, isSample, groupIdMap);

        // 获取项目
        List<ProjectDO> projects = projectDao.listByOrgId(orgSrcId);
        // 处理项目数据
        buildProjectDataAndSave(orgDstId, projects, insIntMemberIdMap, extendFieldIdMap);
    }

    private void buildProjectDataAndSave(String orgDstId, List<ProjectDO> projects, Map<String, String> insMemberIdMap, Map<String, String> extendFieldIdMap) {
        if (CollectionUtils.isEmpty(projects)) {
            return;
        }
        projects.forEach(project -> {
            String projectId = project.getProjectId();
            project.setProjectId(ObjectId.get().toString());
            project.setOrgId(orgDstId);
            String memberId = project.getMemberId();
            if (insMemberIdMap.containsKey(memberId)) {
                project.setMemberId(insMemberIdMap.get(memberId));
            } else {
                log.error("【联系人】项目{}无法找到对应的机构联系人{}的新id", projectId, memberId);
            }
            String accountManager = project.getAccountManager();
            if (insMemberIdMap.containsKey(accountManager)) {
                project.setAccountManager(insMemberIdMap.get(accountManager));
            } else {
                log.error("【联系人】项目{}无法找到对应的客户经理{}的新id", projectId, accountManager);
            }
            // 修改拓展值
            String fieldValList = project.getFieldValList();
            if (!StringUtils.hasText(fieldValList)) {
                return;
            }
            List<ExtendFieldValue> extendFieldValues = JSON.parseArray(fieldValList, ExtendFieldValue.class);
            if (CollectionUtils.isEmpty(extendFieldValues)) {
                return;
            }
            extendFieldValues.forEach(extendField -> {
                String fieldId = extendField.getFieldId();
                if (extendFieldIdMap.containsKey(fieldId)) {
                    extendField.setFieldId(extendFieldIdMap.get(fieldId));
                } else {
                    log.error("【联系人】项目{}无法找到对应的拓展字段{}的新id", projectId, fieldId);
                }
            });
            fieldValList = JSON.toJSONString(extendFieldValues);
            project.setFieldValList(fieldValList);
        });
        projectDao.batchInsert(projects);
    }

    private void buildExtendFieldEnumItemDataAndSave(Collection<ExtendFieldEnumItemDO> extendFieldEnumItems, Map<String, String> extendFieldIdMap) {
        if (CollectionUtils.isEmpty(extendFieldEnumItems)) {
            return;
        }
        extendFieldEnumItems.forEach(extendFieldEnumItem -> {
            extendFieldEnumItem.setFieldEnumId(ObjectId.get().toString());
            String extendFieldId = extendFieldEnumItem.getExtendFieldId();
            if (extendFieldIdMap.containsKey(extendFieldId)) {
                extendFieldEnumItem.setExtendFieldId(extendFieldIdMap.get(extendFieldId));
            }
        });
        extendFieldEnumItemDao.batchInsert(extendFieldEnumItems);
    }

    private void buildExtendFieldDataAndSave(String orgDstId, List<ExtendFieldDO> extendFields, Map<String, String> extendFieldIdMap) {
        if (CollectionUtils.isEmpty(extendFields)) {
            return;
        }
        extendFields.forEach(extendField -> {
            String fieldId = extendField.getFieldId();
            final String newExtendFieldId = ObjectId.get().toString();
            extendField.setFieldId(newExtendFieldId);
            extendFieldIdMap.put(fieldId, newExtendFieldId);
            extendField.setOrgId(orgDstId);
        });
        extendFieldDao.batchInsertField(extendFields);
    }

    private void buildGroupDataAndSave(List<GroupDO> groups, String orgSrcId, String orgDstId,
                                       Map<Long, Long> groupSeqMap,
                                       Map<String, String> extendFieldIdMap,
                                       Map<String, String> labelIdMap,
                                       Map<String, String> labelValueIdMap,
                                       Map<String, String> groupIdMap, boolean isSample) {
        if (CollectionUtils.isEmpty(groups)) {
            return;
        }
        groups.forEach(group -> {
            String groupId = group.getId();
            String newGroupId = ObjectId.get().toString();
            group.setId(newGroupId);
            group.setOrgId(orgDstId);
            Long oldSeq = group.getSeq();
            group.setSeq(null);
            // sample母环境配置的数据皆为示例数据，solution母环境配置的数据皆为非示例数据(对应逻辑为isSample原来是什么现在就是什么)
            if (isSample) {
                group.setIsSample(1);
            }
            // 修改condition
            String conditionStr = group.getCondition();
            if (StringUtils.hasText(conditionStr)) {
                JSONObject condition = JSON.parseObject(conditionStr);
                replaceInfoAndLabelCondition(groupId, condition, groupIdMap, extendFieldIdMap, labelIdMap, labelValueIdMap);
                group.setCondition(condition.toJSONString());
            }
            GroupDO newGroup = groupDao.save(group);
            Long newSeq = newGroup.getSeq();
            groupSeqMap.put(oldSeq, newSeq);
        });
    }

    /**
     * 替换基本信息和标签中的相关id
     *
     * @param id               分组或标签值id，取决于该condition属于谁
     * @param condition        分组条件
     * @param groupIdMap       联系人组织层级旧新id map
     * @param extendFieldIdMap 拓展字段旧新id map
     * @param labelIdMap       标签旧新id map
     * @param labelValueIdMap  标签值旧新id map
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:00 2022/4/1
     */
    private void replaceInfoAndLabelCondition(String id, JSONObject condition, Map<String, String> groupIdMap,
                                              Map<String, String> extendFieldIdMap,
                                              Map<String, String> labelIdMap,
                                              Map<String, String> labelValueIdMap) {
        JSONArray array = condition.getJSONArray(FILTERS);
        if (Objects.isNull(array)) {
            log.error("【联系人】copysample 分组条件filters为null id:{}", id);
            return;
        }
        List<JSONObject> filters = array.toJavaList(JSONObject.class);
        if (CollectionUtils.isEmpty(filters)) {
            log.error("【联系人】copysample 分组条件filters为空列表 id:{}", id);
            return;
        }
        filters.forEach(filter -> {
            if (filter.containsKey(FILTERS)) {
                replaceInfoAndLabelCondition(id, filter, groupIdMap, extendFieldIdMap, labelIdMap, labelValueIdMap);
            } else {
                // 所属组织
                if ("store".equals(filter.getString(NAME))) {
                    replaceGroupId(groupIdMap, filter);
                }
                // 拓展字段
                if (FIELD_VAL_LIST_FIELD_VALUE.equals(filter.getString(NAME))) {
                    replaceExtendFieldId(extendFieldIdMap, filter);
                }
                // 标签
                if (LABEL.equals(filter.getString(SOURCE))) {
                    replaceLabelIdAndLabelValueId(labelIdMap, labelValueIdMap, filter);
                }
            }
        });
        condition.put(FILTERS, filters);
    }

    private void replaceLabelIdAndLabelValueId(Map<String, String> labelIdMap, Map<String, String> labelValueIdMap, JSONObject filter) {
        // 修改标签id映射
        JSONObject detail = filter.getJSONObject(DETAIL);
        String tagId = detail.getString(TAG_ID);
        detail.put(TAG_ID, labelIdMap.get(tagId));
        filter.put(DETAIL, detail);
        // 修改标签值id映射，在“非空”等条件下，找不到是正常的
        String value = filter.getString(VALUE);
        if (labelValueIdMap.containsKey(value)) {
            filter.put(VALUE, labelValueIdMap.get(value));
        }
        JSONArray jsonArray = filter.getJSONArray("choice");
        if (Objects.nonNull(jsonArray)) {
            List<JSONObject> choice = jsonArray.toJavaList(JSONObject.class);
            choice.forEach(item -> {
                item.put(ConditionConstant.ID, labelValueIdMap.get(item.getString(ID)));
                item.put(VALUE, labelValueIdMap.get(item.getString(VALUE)));
            });
            filter.put("choice", choice);
        }
    }

    private void replaceExtendFieldId(Map<String, String> extendFieldIdMap, JSONObject filter) {
        JSONObject detail = filter.getJSONObject(DETAIL);
        String fieldId = detail.getString(FIELD_ID);
        String id = filter.getString(ID);
        if (extendFieldIdMap.containsKey(fieldId)) {
            detail.put(FIELD_ID, extendFieldIdMap.get(fieldId));
        }
        if (extendFieldIdMap.containsKey(id)) {
            filter.put(ID, extendFieldIdMap.get(id));
        }
        filter.put(DETAIL, detail);
    }

    private void replaceGroupId(Map<String, String> groupIdMap, JSONObject filter) {
        JSONArray value = filter.getJSONArray(VALUE);
        if (Objects.nonNull(value)) {
            List<String> newGroupIdList = new ArrayList<>();
            List<String> groupIdList = value.toJavaList(String.class);
            groupIdList.forEach(s -> {
                if (groupIdMap.containsKey(s)) {
                    newGroupIdList.add(groupIdMap.get(s));
                }
            });
            value = JSON.parseArray(JSON.toJSONString(newGroupIdList));
            filter.put(VALUE, value);
        }
    }

    private void buildLabelDataAndSave(List<LabelGroupDO> labelGroups,
                                       List<LabelDO> labels,
                                       List<LabelValueDO> labelValues,
                                       String orgDstId,
                                       Map<String, String> labelIdMap,
                                       Map<String, String> labelValueIdMap,
                                       List<ProjectMapEntity> projectMapEntities,
                                       Map<String, String> groupIdMap,
                                       Map<String, String> extendFieldIdMap,
                                       boolean isSample) {
        if (CollUtil.isEmpty(labelGroups) || CollUtil.isEmpty(labels) || CollUtil.isEmpty(labelValues)) {
            return;
        }
        final Map<String, String> seqProjectIdMap = new HashMap<>();
        if (CollUtil.isNotEmpty(projectMapEntities)) {
            seqProjectIdMap.putAll(projectMapEntities.stream().collect(Collectors.toMap(ProjectMapEntity::getSrcProjectId, ProjectMapEntity::getDstProjectId, (var1, var2) -> var2)));
            log.error("新旧projectId {} ", seqProjectIdMap);
        }

        // 标签根据标签组分组
        Map<String, List<LabelDO>> labelMap = labels.
                stream()
                .collect(Collectors.groupingBy(LabelDO::getLabelGroupId));
        // 标签值根据标签分组
        Map<String, List<LabelValueDO>> labelValueMap = labelValues
                .stream()
                .collect(Collectors.groupingBy(LabelValueDO::getLabelId));
        // 循环处理标签
        List<LabelDO> newLabelList = new ArrayList<>();
        List<LabelValueDO> newLabelValueList = new ArrayList<>();
        labelGroups.forEach(labelGroup -> {
            // 获取标签组id
            String labelGroupId = labelGroup.getId();
            // 设置新的id
            final String newLabelGroupId = ObjectId.get().toString();
            labelGroup.setId(newLabelGroupId);
            // 设置组织id
            labelGroup.setOrgId(orgDstId);
            // sample母环境配置的数据皆为示例数据，solution母环境配置的数据皆为非示例数据(对应逻辑为isSample原来是什么现在就是什么)
            if (isSample) {
                labelGroup.setIsSample(1);
            }
            // 该标签组下的标签
            // 先处理标签condition外的数据，在此过程中获取完整的id映射，再处理condition数据
            List<LabelDO> labelItems = labelMap.get(labelGroupId);
            if (CollUtil.isNotEmpty(labelItems)) {
                Map<String, String> labelIdReverseMap = new HashMap<>();
                labelItems.forEach(label -> {
                    // 获取标签Id
                    String labelId = label.getLabelId();
                    final String newLabelId = StringUtil.getId();
                    // 设置id
                    label.setLabelId(newLabelId);
                    // 设置标签组Id
                    label.setLabelGroupId(newLabelGroupId);
                    // 设置组织id
                    label.setOrgId(orgDstId);
                    // sample母环境配置的数据皆为示例数据，solution母环境配置的数据皆为非示例数据(对应逻辑为isSample原来是什么现在就是什么)
                    if (isSample) {
                        label.setIsSample(1);
                    }
                    // 保存 标签id 映射
                    labelIdMap.put(labelId, newLabelId);
                    labelIdReverseMap.put(newLabelId, labelId);
                    List<LabelValueDO> labelValuesItems = labelValueMap.get(labelId);
                    if (CollUtil.isNotEmpty(labelValuesItems)) {
                        labelValuesItems.forEach(labelValue -> {
                            String labelValueId = labelValue.getLabelValueId();
                            final String newLabelValueId = StringUtil.getId();
                            // 设置id
                            labelValue.setLabelValueId(newLabelValueId);
                            // 设置标签组id
                            labelValue.setLabelGroupId(newLabelGroupId);
                            // 设置标签id
                            labelValue.setLabelId(newLabelId);
                            // 设置组织id
                            labelValue.setOrgId(orgDstId);
                            // sample母环境配置的数据皆为示例数据，solution母环境配置的数据皆为非示例数据(对应逻辑为isSample原来是什么现在就是什么)
                            if (isSample) {
                                labelValue.setIsSample(1);
                            }
                            labelValueIdMap.put(labelValueId, newLabelValueId);
                        });
                    }
                });
                // 处理标签condition
                labelItems.forEach(label -> {
                    String newLabelId = label.getLabelId();
                    String labelId = labelIdReverseMap.get(newLabelId);
                    List<LabelValueDO> labelValuesItems = labelValueMap.get(labelId);
                    if (CollUtil.isNotEmpty(labelValuesItems)) {
                        labelValuesItems.forEach(labelValue -> {
                            // 处理标签condition
                            String newCondition = replaceConditionProjectId(labelValue.getCondition(), seqProjectIdMap);
                            labelValue.setCondition(newCondition);
                            if (StrUtil.isNotEmpty(newCondition)) {
                                JSONObject newJsonCondition = JsonUtil.tryConvertToJSONObject(newCondition);
                                replaceInfoAndLabelCondition(labelValue.getLabelValueId(), newJsonCondition, groupIdMap, extendFieldIdMap, labelIdMap, labelValueIdMap);
                                labelValue.setCondition(newJsonCondition.toJSONString());
                            }
                        });
                        // 保存标签值
                        newLabelValueList.addAll(labelValuesItems);
                    }
                });
                // 标签列表
                newLabelList.addAll(labelItems);
            }
        });
        // 批量保存标签组
        labelGroupDao.batchSaveSampleData(labelGroups);
        // 批量保存标签
        labelDao.batchSaveSampleData(newLabelList);
        // 批量保存标签值
        labelValueDao.batchSaveSampleData(newLabelValueList);
    }

    /**
     * 替换 condition 的projectId
     * 一个condiiton 只会有一个 问卷项目 只在第一层 替换掉就可以了
     *
     * @param condition
     */
    private String replaceConditionProjectId(String condition, Map<String, String> projectIdMap) {
        if (StrUtil.isNotEmpty(condition)) {
            JSONObject conditionObj = JsonUtil.tryConvertToJSONObject(condition);
            List<JSONObject> filters = (List<JSONObject>) conditionObj.get(FILTERS);
            if (CollUtil.isNotEmpty(filters)) {
                filters.forEach(item -> {
                    if (item.containsKey("project_id")) {
                        String projectId = item.getString("project_id");
                        String newProjectId = projectIdMap.getOrDefault(projectId, "");
                        if (StrUtil.isNotEmpty(newProjectId)) {
                            item.put("project_id", newProjectId);
                        } else {
                            log.error("【联系人】项目{}无法找到对应的新id, newProjectId:{}", projectId, newProjectId);
                        }
                    }
                });
                conditionObj.put(FILTERS, filters);
            }
            if (conditionObj.containsKey("project_id")) {
                String projectId = conditionObj.getString("project_id");
                String newProjectId = projectIdMap.getOrDefault(projectId, "");
                if (StrUtil.isNotEmpty(newProjectId)) {
                    conditionObj.put("project_id", newProjectId);
                } else {
                    log.error("【联系人】项目{}无法找到对应的新id, newProjectId:{}", projectId, newProjectId);
                }
            }
            return JsonUtil.tryConvertToJSONString(conditionObj);
        }
        return condition;
    }

    private void buildMemberDataAndSave(List<MemberDO> memberList,
                                        List<FootprintDO> footprints,
                                        final String orgSrcId,
                                        final String orgDstId,
                                        List<RespondentSeq> seqList,
                                        Map<String, String> ticketIdMap,
                                        Map<String, String> labelIdMap,
                                        Map<String, String> labelValueIdMap,
                                        Map<Long, Long> groupSeqMap,
                                        Map<String, String> insIntMemberIdMap,
                                        Map<String, String> extendFieldIdMap,
                                        boolean isSample, Map<String, String> groupIdMap) {
        final Map<String, String> seqMap = new HashMap<>();
        final Map<String, String> seqProjectIdMap = new HashMap<>();
        if (CollUtil.isNotEmpty(seqList)) {
            seqMap.putAll(seqList.stream().collect(Collectors.toMap(RespondentSeq::getSrcSeq, RespondentSeq::getDstSeq, (var1, var2) -> var2)));
            seqProjectIdMap.putAll(seqList.stream().collect(Collectors.toMap(RespondentSeq::getDstSeq, RespondentSeq::getDstProjectId, (var1, var2) -> var2)));
        }
        if (CollUtil.isNotEmpty(memberList)) {
            // 循环处理联系人
            List<FootprintDO> newFootprintList = new ArrayList<>();
            Map<String, String> ticketMap = new HashMap<>();
            Map<String, String> respondentMap = new HashMap<>();
            memberList.forEach(member -> {
                String memberId = member.getId();
                final String newMemberId = new ObjectId().toString();
                // 修改 orgId
                member.setOrgId(orgDstId);
                // 设置id
                member.setId(newMemberId);
                if (MemberTypeEnum.INSTITUTION.getIndex() == member.getMemberType() ||
                        MemberTypeEnum.INTERIOR.getIndex() == member.getMemberType()) {
                    insIntMemberIdMap.put(memberId, newMemberId);
                }
                // sample母环境配置的数据皆为示例数据，solution母环境配置的数据皆为非示例数据(对应逻辑为isSample原来是什么现在就是什么)
                if (isSample) {
                    member.setSource("sample");
                }
                // 设置编号
                member.setMemberNo(memberService.getMemberNo(member.getOrgId(), member.getMemberType()));
                //修改groups字段的seq映射
                String groups = member.getGroups();
                if (StringUtils.hasText(groups)) {
                    List<Long> tempGroups = JSON.parseArray(groups, Long.class);
                    List<Long> newGroups = new ArrayList<>();
                    for (Long oldGroupSeq : tempGroups) {
                        if (groupSeqMap.containsKey(oldGroupSeq)) {
                            newGroups.add(groupSeqMap.get(oldGroupSeq));
                        }
                    }
                    groups = JSON.toJSONString(newGroups);
                    member.setGroups(groups);
                }
                // 修改个人联系人组织层级映射
                if (MemberTypeEnum.INDIVIDUAL.getIndex() == member.getMemberType()) {
                    String storeId = member.getStoreId();
                    String newStoreId = groupIdMap.get(storeId);
                    if (StringUtils.hasText(newStoreId)){
                        member.setStoreId(newStoreId);
                    }
                }
                // 修改拓展字段
                String fieldValList = member.getFieldValList();
                if (StringUtils.hasText(fieldValList)) {
                    List<ExtendFieldDTO> extendFields = JSON.parseArray(fieldValList, ExtendFieldDTO.class);
                    if (!CollectionUtils.isEmpty(extendFields)) {
                        extendFields.forEach(extendField -> {
                            String fieldId = extendField.getId();
                            if (extendFieldIdMap.containsKey(fieldId)) {
                                extendField.setId(extendFieldIdMap.get(fieldId));
                            } else {
                                log.error("【联系人】联系人{}无法找到对应的拓展字段{}的新id", memberId, fieldId);
                            }
                        });
                        fieldValList = JSON.toJSONString(extendFields);
                        member.setFieldValList(fieldValList);
                    }
                }
                List<LabelValueId> labels = null;
                String labelStr = member.getLabels();
                if (StrUtil.isNotEmpty(labelStr)) {
                    labels =
                            JSONArray.parseArray(labelStr, LabelValueId.class);
                }
                if (CollUtil.isNotEmpty(labels)) {
                    labels.forEach(label -> {
                        if (labelIdMap.containsKey(label.getLabelId())) {
                            // 标签id
                            label.setLabelId(labelIdMap.get(label.getLabelId()));
                        }
                        if (labelValueIdMap.containsKey(label.getId())) {
                            // 标签值id
                            label.setId(labelValueIdMap.get(label.getId()));
                        }
                    });
                    // 设置标签信息
                    member.setLabels(JSONObject.toJSONString(labels));
                }
                if (member.getMemberType() == MemberTypeEnum.INDIVIDUAL.getIndex()) {
                    // 只有个人联系人才有足迹点
                    if (CollUtil.isNotEmpty(footprints)) {
                        Map<String, List<FootprintDO>> footprintMap =
                                footprints.stream().collect(Collectors.groupingBy(FootprintDO::getMemberId));
                        List<FootprintDO> footprintsItems = footprintMap.get(memberId);
                        if (CollUtil.isNotEmpty(footprintsItems)) {
                            List<FootprintDO> newFootprint = new ArrayList<>();
                            footprintsItems.forEach(item -> {
                                // 设置id
                                item.setId(StringUtil.getId());
                                // 联系人id
                                item.setMemberId(newMemberId);
                                // 组织id
                                item.setOrgId(orgDstId);
                                // 是否示例数据
                                item.setIsSample(1);
                                if (item.getType() == FootprintTypeEnum.MEMBER.getIndex()) {
                                    // 联系人
                                    item.setSourceKey(newMemberId);
                                    newFootprint.add(item);
                                }
                                if (item.getType() == FootprintTypeEnum.TICKET.getIndex()) {
                                    // 工单
                                    if (CollUtil.isNotEmpty(ticketIdMap)) {
                                        String ticketId = ticketIdMap.get(item.getSourceKey());
                                        if (StrUtil.isNotEmpty(ticketId)) {
                                            item.setSourceKey(ticketId);
                                            newFootprint.add(item);
                                            ticketMap.put(ticketId, newMemberId);
                                        }
                                    }
                                }
                                if (item.getType() == FootprintTypeEnum.SURVEY.getIndex()) {
                                    // 问卷
                                    if (CollUtil.isNotEmpty(seqMap)) {
                                        String seq = seqMap.get(item.getSourceKey());
                                        if (StrUtil.isNotEmpty(seq)) {
                                            item.setSourceKey(seq);
                                            // 处理 content
                                            String content = item.getContent();
                                            if (StrUtil.isNotBlank(content)) {
                                                // 转换成json
                                                JSONObject contentJson = JSONObject.parseObject(content);
                                                if (ObjectUtil.isNotEmpty(contentJson)) {
                                                    if (contentJson.containsKey("project_id")) {
                                                        // 替换原有的projectId
                                                        contentJson.put("project_id", seqProjectIdMap.get(seq));
                                                    }
                                                    String contentStr = JSONObject.toJSONString(contentJson);
                                                    item.setContent(contentStr);
                                                }
                                            }
                                            newFootprint.add(item);
                                            respondentMap.put(seq, newMemberId);
                                        }
                                    }
                                }
                            });
                            newFootprintList.addAll(newFootprint);
                        }
                    }
                }
            });
            // 批量保存联系人
            memberDao.batchSave(memberList);
            // 创建联系人数据源
            buildMemberDateSource(memberList, orgDstId);
            // 批量保存足迹点
            footprintDao.batchSaveSampleData(newFootprintList);
            // 更新工单memberId(会有多个工单)
            ticketClient.updateTicket(ticketMap);
            // 更新答卷memberId(只有一个答卷)
            if (CollUtil.isNotEmpty(respondentMap)) {
                respondentMap.forEach((seq, memberId) -> {
                    surveyClient.updateRespondentMemberIdBySeq(seq, memberId, seqProjectIdMap.get(seq));
                });
            }
        }
    }

    /**
     * 创建联系人数据源
     *
     * @param memberList
     * @param orgId
     */
    private void buildMemberDateSource(List<MemberDO> memberList, String orgId) {
        if (CollUtil.isNotEmpty(memberList)) {
            ServiceResult<OrganizationDTO> organization = memberUtil.getOrganization(orgId);
            OrganizationDTO dto = organization.getData();
            memberList.forEach(member -> {
                // 推送创建的联系人
                MemberMessage message = MemberUtil.memberDoToMemberMessage(member);
                message.setOrgCode(dto.getCode());
                message.setOrgName(dto.getName());
                String identityType = "";
                switch (EnumUtil.getEnumByIndex(MemberTypeEnum.class, member.getMemberType())) {
                    case INSTITUTION:
                        message.setIdentityType("企业对接人");
                        message.setNumberId("000");
                        break;
                    case INTERIOR:
                        identityType = ObjectUtil.isNotEmpty(member.getEmployeeStatus()) ? EMPLOYEE_STATUS_MAP.get(member.getEmployeeStatus()) : "";
                        message.setIdentityType(identityType);
                        break;
                    case INDIVIDUAL:
                        identityType = memberUtil.getIdentityType(member.getPhone(), member.getOrgId(), member.getEmail());
                        message.setIdentityType(identityType);
                        break;
                }
                memberUtil.publishCreateMember(message);
            });
        }
    }
}
